import { ADDTOCAR, ADDTOCARCOUNT, SUBTOCARCOUNT, SWITCHCARSTATE, SWITCHCARSTATEALL } from '../constants/car'
import Taro from '@tarojs/taro'
const INITIAL_STATE = {
	carList: JSON.parse(Taro.getStorageSync('carList') || '[]')
}
// action => { type, payload }	
export default function counter(state = INITIAL_STATE, action) {
	switch (action.type) {
		/* 购物车商品： id, title, desc, price , count, state, messageList, image */ 
		case ADDTOCAR:
			// 处理加入购物车逻辑
			// 1. 购物车是否存在该商品
			const goods = state.carList.find(v => v.id === action.payload.id)
			// 2. 存在
			if(goods) {
				goods.count++
			} 
			// 3. 不存在
			else {
				state.carList.push(action.payload)
			}
			return {
				...state,
				carList: [...state.carList]
			}
		case ADDTOCARCOUNT: {
			const goods = state.carList.find(v => v.id === action.payload.id);
			if(goods) goods.count++
			return {
				...state,
				carList: [...state.carList]
			}
		}
		case SUBTOCARCOUNT: {
			const goods = state.carList.find(v => v.id === action.payload.id);
			if(goods) goods.count--
			return {
				...state,
				carList: [...state.carList]
			}
		}
		case SWITCHCARSTATE: {
			const goods = state.carList.find(v => v.id === action.payload.id);
			if(goods) goods.state = !goods.state
			return {
				...state,
				carList: [...state.carList]
			}
		}
		case SWITCHCARSTATEALL: {
			state.carList.forEach(v => {
				v.state = action.payload
			})
			return {
				...state,
				carList: [...state.carList]
			}
		}
		default:
			return state
	}
}
